import { Inject, Provide, Logger } from '@midwayjs/decorator';
import { BaseService, CoolCommException } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository, In, Not } from 'typeorm';
import { UserSectEntity } from '../entity/sect';
import { UserDataEntity } from '../entity/data';
import { UserRaceEntity } from '../entity/race';
import { UserItemsEntity } from '../entity/items';
import { ILogger } from '@midwayjs/logger';
/**
 * 用户信息
 */
@Provide()
export class UserSectsService extends BaseService {
  @Logger()
  logger: ILogger;

  @InjectEntityModel(UserSectEntity)
  UserSectEntity: Repository<UserSectEntity>;

  @InjectEntityModel(UserDataEntity)
  UserDataEntity: Repository<UserDataEntity>;

  @InjectEntityModel(UserRaceEntity)
  UserRaceEntity: Repository<UserRaceEntity>;

  @InjectEntityModel(UserItemsEntity)
  UserItemsEntity: Repository<UserItemsEntity>;


  /**
   * 获取用户信息
   * @param id
   * @returns
   */
  async list(data) {
    const { raceId } = data;
    return await this.UserSectEntity.findBy({
      raceId
    })
  }

  async getChatRace() {
    const data = await this.UserRaceEntity.createQueryBuilder('race')
      .leftJoinAndSelect(UserDataEntity, 'user', 'race.id = user.raceId')
      .select(['race', 'user'])
      .getRawMany();
    return Object.values(data.reduce((pre, val) => {
      if (!pre[val.race_id]) {
        pre[val.race_id] = {
          name: val.race_name,
          value: 0
        }
      }
      pre[val.race_id].value += 1;
      return pre;
    }, {}))
  }

  async getChatSect() {
    const data = await this.UserSectEntity.createQueryBuilder('sect')
      .leftJoinAndSelect(UserDataEntity, 'user', 'sect.id = user.sectId')
      .select(['sect', 'user'])
      .getRawMany();
    return Object.values(data.reduce((pre, val) => {
      if (!pre[val.sect_id]) {
        pre[val.sect_id] = {
          name: val.sect_name,
          value: 0
        }
      }
      pre[val.sect_id].value += 1;
      return pre;
    }, {}))
  }

  // 统计所有用户金币
  async taskPlay() {
    const data = await this.UserDataEntity.find({
      select: {
        nickName: true,
        gold: true
      }
    });
    // this.logger.info(`当前所有用户金币统计：${JSON.stringify(data)}`);
    return `当前所有用户金币统计：${JSON.stringify(data)}`;
  }

  // 获取背包物品
  async getGoodsItems(uid) {
    return this.UserItemsEntity.findBy({
      uid
    })
  }
  // 更新背包物品
  async setGoodsItems(data) {
    // 删除物品数据
    await this.UserItemsEntity.delete({
      id: Not(In(data.map(item => item.id)))
    })
    // 更新物品数据
    return await this.UserItemsEntity.save(data);
  }
}


